package com.kun.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.common.constant.UserConstant;
import com.kun.domain.TFollowingGroup;
import com.kun.domain.TUser;
import com.kun.domain.TUserFollowing;
import com.kun.domain.TUserInfo;
import com.kun.service.mapper.TUserFollowingMapper;
import com.kun.service.service.ITFollowingGroupService;
import com.kun.service.service.ITUserFollowingService;
import com.kun.service.service.ITUserService;
import com.kun.service.util.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class TUserFollowingServiceImpl extends ServiceImpl<TUserFollowingMapper, TUserFollowing>
        implements ITUserFollowingService {

    private final ITFollowingGroupService itFollowingGroupService;
    private final ITUserService itUserService;

    public TUserFollowingServiceImpl(ITFollowingGroupService itFollowingGroupService, ITUserService itUserService) {
        this.itFollowingGroupService = itFollowingGroupService;
        this.itUserService = itUserService;
    }

    /**
     * 获取用户关注列表
     */
    @Override
    public List<TFollowingGroup> getUserFollowings() {
        Long userId = UserContext.getUserId();
        // 根据UserId查询出来所有的关注人包含关注人信息
        List<TUserFollowing> followingByUserId = findFollowingByUserId(new TUserFollowing(userId, null));
        // 根据用户ID查询所有的群组
        List<TFollowingGroup> tFollowingGroups = itFollowingGroupService.getUserFollowingGroups(userId.toString());
        // 所有分组列表
        List<TFollowingGroup> followingGroups = new ArrayList<>();
        // 所有关注人的用户信息
        List<TUserInfo> list = followingByUserId.stream().map(TUserFollowing::getUserInfo).toList();
        TFollowingGroup tFollowingGroup1 = new TFollowingGroup(0L, userId, UserConstant.ALL_FOLLOWING_NAME,
                UserConstant.ALL_FOLLOWING_TYPE, LocalDateTime.now());
        tFollowingGroup1.setFollowingUserInfoList(list);
        followingGroups.add(tFollowingGroup1);

        // 遍历所有的分组
        tFollowingGroups.forEach(tFollowingGroup -> {

            // 设置当前分组的关注人信息
            tFollowingGroup.setFollowingUserInfoList(
                    // 查找当前分组的关注人
                    followingByUserId.stream()
                            .filter(tUserFollowing -> tUserFollowing.getGroupId().equals(tFollowingGroup.getId()))
                            .map(TUserFollowing::getUserInfo).toList());
        });
        return followingGroups;
    }

    /**
     * 添加用户关注
     */
    @Override
    @Transactional
    public boolean addUserFollowings(TUserFollowing tUserFollowing) {
        tUserFollowing.setUserId(UserContext.getUserId());
        // 获取用户组，如果用户组不存在，加入到默认组
        Long groupId = tUserFollowing.getGroupId();
        if (groupId == null) {
            TFollowingGroup groupById = itFollowingGroupService.getGroupByTypeId(UserConstant.DEFAULT_FOLLOW_GROUP_TYPE);
            Assert.isTrue(groupById != null, "默认分组不存在");
            tUserFollowing.setGroupId(groupById.getId());
        } else {
            TFollowingGroup followGroupById = itFollowingGroupService.getFollowGroupById(groupId);
            Assert.isTrue(followGroupById != null, "关注分组不存在");
        }
        TUser user = itUserService.getUserById(tUserFollowing.getFollowingId());
        Assert.isTrue(user != null, "关注用户不存在");
        tUserFollowing.setCreateTime(LocalDateTime.now());
        return save(tUserFollowing);
    }

    /**
     * 获取用户粉丝列表，检查互关状态
     */
    @Override
    public List<TUserFollowing> getUserFans() {
        Long userId = UserContext.getUserId();
        return getUserFans(userId);
    }

    @Override
    public List<TUserFollowing> getUserFans(Long userId) {
        // 第一步：获取我关注的和关注我的
        List<TUserFollowing> followingAndFollowers = getUserFollowingsAndFollowers(userId.toString());
        // 获取关注我的粉丝
        List<TUserFollowing> tUserFollowings = followingAndFollowers.stream()
                .filter(tUserFollowing -> tUserFollowing.getFollowingId().equals(userId)).toList();
        // 获取我关注的
        Set<Long> list = followingAndFollowers.stream()
                .filter(tUserFollowing -> tUserFollowing.getUserId().equals(userId))
                .map(TUserFollowing::getFollowingId).collect(Collectors.toSet());
        // 第二步：设置互关，true 互关
        tUserFollowings.forEach(tUserFollowing -> tUserFollowing.setFollowed(list.contains(tUserFollowing.getUserId())));
        return tUserFollowings;
    }

    /**
     * 分页获取用户信息列表
     */
    @Override
    public String pageUserInfo(TUserFollowing tUserFollowing) {
        // 没什么意义，需要时在写吧
        return "";
    }

    /**
     * 获取我关注的和关注我的
     */
    private List<TUserFollowing> getUserFollowingsAndFollowers(String userId) {
        return baseMapper.getUserFollowingsAndFollowers(userId);
    }

    /**
     * 根据UserId查询出来所有的关注人包含关注人信息
     */
    public List<TUserFollowing> findFollowingByUserId(TUserFollowing tUserFollowing) {
        return baseMapper.findFollowingByUserId(tUserFollowing);
    }

    /**
     * 根据UserId查询出来所有的关注人
     */
    private List<TUserFollowing> getUserFollowingByUserId(String userId) {
        return lambdaQuery().eq(TUserFollowing::getUserId, userId).list();
    }

    /**
     * 根据UserId查询出来所有的关注人的ID
     */
    private List<Long> getUserFollowingIdsByUserId(String userId) {
        return getUserFollowingByUserId(userId).stream().map(TUserFollowing::getFollowingId).toList();
    }
}
